package com.chub.resp;

import lombok.Data;

/**
 * @author : chub
 * @version : V1.0.0
 * @fileName : R.java
 * @description : 统一响应类
 * @createTime : 2022-04-23 10:23
 */
@Data
public class R<T> {
    private Boolean success;

    private Integer code;

    private String message;

    /**
     * 数据信息
     */
    private T data;

    // private Map<String, Object> data = new HashMap<>();

    // 构造器私有
    private R() {
    }

    public  R(REnum rEnum, T data) {
        this.code = rEnum.getCode();
        this.message = rEnum.getMessage();
        this.data = data;
    }

    // 通用返回成功
    public static <T> R<T> ok() {
        R r = new R();
        r.setSuccess(REnum.SUCCESS.getSuccess());
        r.setCode(REnum.SUCCESS.getCode());
        r.setMessage(REnum.SUCCESS.getMessage());
        return r;
    }

    // 通用返回失败，未知错误
    public static R error() {
        R r = new R();
        r.setSuccess(REnum.UNKNOWN_ERROR.getSuccess());
        r.setCode(REnum.UNKNOWN_ERROR.getCode());
        r.setMessage(REnum.UNKNOWN_ERROR.getMessage());
        return r;
    }

    // 通用返回失败，已知错误
    public static R error(REnum rEnum) {
        R r = new R();
        r.setSuccess(rEnum.getSuccess());
        r.setCode(rEnum.getCode());
        r.setMessage(rEnum.getMessage());
        return r;
    }

    // 设置结果，形参为结果枚举
    public static R setResult(REnum result) {
        R r = new R();
        r.setSuccess(result.getSuccess());
        r.setCode(result.getCode());
        r.setMessage(result.getMessage());
        return r;
    }

    /**
     * ------------使用链式编程，返回类本身-----------
     **/

    // 自定义返回数据
    public R data(T data) {
        this.setData(data);
        return this;
    }

    // // 通用设置data
    // public R data(String key, Object value) {
    //     this.data.put(key, value);
    //     return this;
    // }

    // 自定义状态信息
    public R message(String message) {
        this.setMessage(message);
        return this;
    }

    // 自定义状态码
    public R code(Integer code) {
        this.setCode(code);
        return this;
    }

    // 自定义返回结果
    public R success(Boolean success) {
        this.setSuccess(success);
        return this;
    }
}
